package com.tianjian.common.coding;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tianjian.common.Config;

@Service
public class Coding {

	private static Map<String, List<Bmb>> CODING = new HashMap<String, List<Bmb>>();

	@Autowired
	private CodingMapper codingMapper;

	public static List<Bmb> list(String type) {
		if (type == null || type.length() == 0) return null;
		Coding coding = init();
		type = type.toUpperCase();
		List<Bmb> codes = CODING.get(type);
		if (codes == null) {
			codes = coding.codingMapper.select(type);
			CODING.put(type, codes);
		}
		return codes;
	}

	public static Object get(String type, String value) {
		List<Bmb> codes = CODING.get(type);
		for (int i = 0; i < codes.size(); i++) {
			Bmb bmb = codes.get(i);
			if (value.equals(bmb.id)) {
				return bmb.text;
			}
		}
		return null;
	}

	private static Coding init() {
		HttpSession session = ServletActionContext.getRequest().getSession();
		Coding coding = (Coding) session.getAttribute(Config.SESSION_CODING);
		if (coding == null) {
			coding = new Coding();
			WebApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext());
//			ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
			coding.codingMapper = (CodingMapper) ac.getBean("codingMapper");
			session.setAttribute(Config.SESSION_CODING, coding);
		}
		return coding;
	}

}
